package com.gogowan.agroenterprise.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.Contacts;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.contorl.Base64;
import com.gogowan.agroenterprise.contorl.Enum.Temp;
import com.gogowan.agroenterprise.contorl.HTTPCommit;
import com.gogowan.agroenterprise.model.Message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ioid.utils.JsonUtils;
import com.ioid.utils.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class Utils {

	/**
	 * 加密密码
	 */
	private final static String KEY = "12345678";
	/**
	 * 加密向量
	 */
	private final static String IV = "12345678";

	public final static String MYCARD = "MYCARD";

	public final static String ENCODE_CONTENT = "ENCODE_CONTENT";

	public final static String PROMOTION = "PROMOTION";
	public static final int save_Result_Code=20102;

	public static final String[] METHODS_PROJECTION = { BaseColumns._ID, // 0
			Contacts.ContactMethodsColumns.KIND, // 1
			Contacts.ContactMethodsColumns.DATA, // 2
	};

	public static final int PHONES_NUMBER_COLUMN = 1;

	public static final String[] PHONES_PROJECTION = { BaseColumns._ID, // 0
			Contacts.PhonesColumns.NUMBER // 1
	};
	public static final int METHODS_KIND_COLUMN = 1;
	public static final int METHODS_DATA_COLUMN = 2;

	/**
	 * 安卓市场
	 */
	public static final int ANDROID_MARKET = 0;
	/**
	 * 安智市场
	 */
	public static final int ANZHI_MARKET = 1;
	/**
	 * 机锋市场
	 */
	public static final int GFAN_MARKET = 2;
	private static long lastClickTime = 0;

	/**
	 * 读取本地图片
	 *
	 * @return
	 */
	public static Intent goLocalImage(Activity activity) {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = 200;
		if (dm.widthPixels < dm.heightPixels) {
			width = dm.widthPixels;
		} else {
			width = dm.heightPixels;
		}
		Log.d("width", width + "");
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		// intent.putExtra("aspectX", 1);
		// intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", width / 2);
		intent.putExtra("outputY", width / 2);
		intent.putExtra("return-data", true);
		return intent;
		// startActivityForResult(intent, i);
	}
	public static String HttpRed(boolean b,String str){
		if (b){
			return "<font color='#f50d05'>"+str+"</font>";
		}
		return str;
	}
	public static String Httpblue(boolean b,String str){
		if (b){
			return "<font color='#007bbb'>"+str+"</font>";
		}
		return str;
	}
	public static boolean isDClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 300) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
	/**
	 * 通过身份证得到生日
	 *
	 * @param isNumber 身份证
	 * @return 结果:0,生日；1,错误信息
	 */
	public static String getIsNumberToBirthday(String isNumber) {
		if (isEmpty(isNumber)) {
			return "请输入身份证号";
		}
		String date = "";
		String strYear = "";// 年
		String strMonth = "";// 月
		String strDay = "";// 日
		String str = "";
		if (isNumber.length() == 18) {
			String num = isNumber.substring(6, 14);
			strYear = num.substring(0, 4);
			strMonth = num.substring(4, 6);
			strDay = num.substring(6, 8);
			str = isNumber.substring(0, 17);
			// date = num.substring(0, 4) + "-" + num.substring(4, 6) + "-"
			// + num.substring(6, 8);
		} else if (isNumber.length() == 15) {
			String num = isNumber.substring(6, 12);
			strYear = "19" + num.substring(0, 2);
			strMonth = num.substring(2, 4);
			strDay = num.substring(4, 6);
			str = isNumber;
			// date = "19" + num.substring(0, 2) + "-" + num.substring(2, 4) +
			// "-"
			// + num.substring(4, 6);
		}
		// 除最后以外都为数字
		if (!isNumeric(str)) {
			return "身份证15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。";
		}
		date = strYear + "-" + strMonth + "-" + strDay;
		try {
			if (Integer.parseInt(strYear) < 1800
					|| Integer.parseInt(strYear) > 2100) {
				return "身份证生日不在（1800-2100）年的有效范围";
			} else if (Integer.parseInt(strMonth) > 12
					|| Integer.parseInt(strMonth) == 0) {
				return "身份证月份无效";
			} else if (Integer.parseInt(strDay) > 31
					|| Integer.parseInt(strDay) == 0) {
				return "身份证日期无效";
			}
		} catch (NumberFormatException e) {
			return "身份证日期解析错误";
		}
		// catch (java.text.ParseException e) {
		// resultInfo.setResultinfo("身份证日期解析错误");
		// return resultInfo;
		// }
		return null;
	}

	/**
	 * 功能：判断字符串是否为数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (isNum.matches()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 1-9转换成01-09
	 *
	 * @param time
	 * @return 字符串
	 */
	public static String formatTime(int time) {

		String timeStr = "";
		if (time < 10) {
			timeStr = "0" + String.valueOf(time);
		} else {
			timeStr = String.valueOf(time);
		}
		return timeStr;
	}

	/**
	 * 2011-10-12转化成数组：[年，月，日]
	 *
	 * @param str 字符串
	 * @return 数组
	 */
	public static int[] forNums(String str) {
		String[] date = str.trim().split("-");
		int nums[] = new int[date.length];
		try {

			for (int i = 0; i < date.length; i++) {
				nums[i] = Integer.parseInt(date[i]);
			}
		} catch (Exception e) {

		}
		// Log.d("date-----------", ""+nums[0]+"-"+nums[1]+"-"+nums[2]);
		return nums;
	}

	public static int[] forTimeNums(String str) {
		String[] date = str.trim().split(":");
		int nums[] = new int[date.length];
		try {

			for (int i = 0; i < date.length; i++) {
				nums[i] = Integer.parseInt(date[i]);
			}
		} catch (Exception e) {

		}
		// Log.d("date-----------", ""+nums[0]+"-"+nums[1]+"-"+nums[2]);
		return nums;
	}

	/**
	 * 加密
	 *
	 * @param value 内容
	 * @return 加密后内容
	 */
	public static java.lang.String encrypt(String value) {
		byte[] key = null, iv = null;
		try {
			key = KEY.getBytes("utf-8");
			iv = IV.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {

		}
		String result = null;
		byte[] tmpOriginalStr = null;
		try {
			if (!isEmpty(value)) {
				tmpOriginalStr = value.getBytes("utf-8");
				SecretKeyFactory keyFactory = SecretKeyFactory
						.getInstance("DES");
				DESKeySpec dks = new DESKeySpec(key);
				SecretKey secretKey = keyFactory.generateSecret(dks);
				IvParameterSpec param = new IvParameterSpec(iv);
				Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
				cipher.init(Cipher.ENCRYPT_MODE, secretKey, param);
				byte[] tmpEncypt = cipher.doFinal(tmpOriginalStr);
				if (tmpEncypt != null) {
					// BASE64Encoder bse=new BASE64Encoder();
					// result=bse.encode(tmpEncypt);
					byte[] b = Base64.encode(tmpEncypt, 0);
					result = new String(b, "utf-8");
				}
			}
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 解密
	 *
	 * @param value 加密内容
	 * @return 解密后内容
	 */
	public static java.lang.String decrypt(String value) {
		byte[] key = null, iv = null;
		try {
			key = KEY.getBytes("utf-8");
			iv = IV.getBytes("utf-8");
		} catch (UnsupportedEncodingException e1) {

		}
		String result = null;
		byte[] tmpEncrypStr = null;
		try {
			if (!isEmpty(value)) {
				// BASE64Decoder bd=new BASE64Decoder();
				// tmpEncrypStr =bd.decodeBuffer(encrypStr);
				tmpEncrypStr = Base64.decode(value, 0);
				SecretKeyFactory keyFactory = SecretKeyFactory
						.getInstance("DES");
				DESKeySpec dks = new DESKeySpec(key);
				SecretKey secretKey = keyFactory.generateSecret(dks);
				IvParameterSpec param = new IvParameterSpec(iv);
				Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
				cipher.init(Cipher.DECRYPT_MODE, secretKey, param);
				byte[] tmpDecrypt = cipher.doFinal(tmpEncrypStr);
				if (tmpDecrypt != null) {
					result = new String(tmpDecrypt, "utf-8");
				}
			}
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 字符串是否为空
	 *
	 * @param str 字符串
	 * @return 是或否
	 */
	public static boolean isEmpty(String str) {
		if (str == null) {
			return true;
		} else if (str.equals("") || str.equals("null")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 得到枚举值
	 *
	 * @param str
	 * @return 枚举值
	 */
	public static int getTempValue(Temp str) {
		int id = 0;
		for (Temp t : Temp.values()) {
			/* 通过getValue()取得相关枚举的值 */
			// System.out.println(t+"的值是"+t.getValue());
			if (t.equals(str)) {
				id = t.getValue();
			}
		}
		return id;
	}

	/**
	 * post提交
	 *
	 * @param url
	 * @param message
	 * @return result
	 */
	public static String postCommit(String url, Object message) {
		String result = "";
		try {
			HTTPCommit commit = new HTTPCommit(url);
			String messageStr = toJSON(message);
			PalUtils.showLogE("requestMsg------------>", messageStr);
			byte[] b = commit.PostCommit(messageStr, 60000);
			if (b != null) {
				result = new String(b, "utf-8");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return result;
	}
	/**
	 * get提交
	 *
	 * @param url
	 * @return result
	 */
	public static String getCommit(String url) {
		String result = "";
		try {
			HTTPCommit commit = new HTTPCommit(url);
			result = commit.GetCommit(60000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return result;
	}
	/**
	 * post提交
	 *
	 * @param url
	 *            地址
	 * @param message
	 * @param timeout
	 *            延迟时间
	 * @return
	 */
	public static String postCommit(String url, Message message, int timeout) {
		String result = "";
		try {
			HTTPCommit commit = new HTTPCommit(url);
			String messageStr = toJSON(message);
			byte[] b = commit.PostCommit(messageStr, timeout);
			if (b != null) {
				result = new String(b, "utf-8");
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return result;
	}

	/**
	 * json转换成对象
	 *
	 * @param jsonString json字符串
	 * @param targetType 对象类型
	 * @return 对象
	 */
	public static Object fromJSON(String jsonString, Type targetType) {
		Object object = null;
		GsonBuilder builder = new GsonBuilder();
		builder.serializeNulls();
		Gson gson = builder.create();
		object = gson.fromJson(jsonString, targetType);

		return object;
	}

	/**
	 * 对象转换成json
	 *
	 * @param objectVal 对象
	 * @return json字符串
	 */
	public static String toJSON(Object objectVal) {
		GsonBuilder builder = new GsonBuilder();
		builder.serializeNulls();
		Gson gson = builder.create();
		String gsonStr = gson.toJson(objectVal);
		PalUtils.showLogE("RequestJson------>", gsonStr);
		return gsonStr;
	}
	/**
	 * 设置json本地缓存提交数据格式
	 *
	 * @param objectVal 对象
	 * @return json字符串
	 */
	public static JSONObject getDiffData(int code,String typeString, String msg, String user, Object objectVal) {
		JSONObject jo=new JSONObject();
		try {
			jo.put("code",code);
			jo.put("msg",msg);
			jo.put("data",objectVal);
			jo.put("user",user);
			jo.put("typeString",typeString);
			jo.put("time",getCurrentTime());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return jo;
	}
	/**
	 * json转换成Message对象
	 * json转换成Message对象
	 *
	 * @param json
	 * @return Message
	 */
	public static Message jsonToMessage(String json) {
		Message message = new Message();
		message = (Message) fromJSON(json, Message.class);// 转换成消息盒子
		return message;
	}

	/**
	 * 得到消息内容
	 *
	 * @param message
	 * @return Content
	 */
	public static String getMessageContent(Message message, boolean isEncrypt) {
		String content = message.getMessagebody().getContent();
		if (isEncrypt)// 是否加密
		{
			content = decrypt(content);
		}
		return content;
	}

	/**
	 * 得到消息内容
	 *
	 * @param message
	 * @return Content
	 */
	public static String getMessageContent(Message message) {
//		boolean isEncrypt = message.getMessagehead().getIsEncrypt();// 是否加密
		String content = message.getData();
		if (false)// 是否加密
		{
			content = decrypt(content);
		}
		return content;
	}

	/**
	 * 输入框错误提示
	 *
	 * @param et
	 *            输入框控件
	 * @param text
	 *            提示内容
	 */
	public static void editTextError(EditText et, String text) {
		et.setError(text);
		et.requestFocus();
	}

	/**
	 * 按钮错误提示
	 *
	 * @param btn
	 *            按钮控件
	 * @param text
	 *            提示内容
	 */
	public static void editTextError(Button btn, String text) {
		btn.setError(text);
		btn.requestFocus();
	}

	/**
	 * 日期格式化测试
	 *
	 * @param str
	 *            日期（yyyy-MM-dd hh:mm:ss）
	 * @param fomcat
	 *            日期格式
	 * @return 日期（yyyy-MM-dd）
	 */
	public static String getDateFormat(String str, String fomcat) {
		// if(isEmpty(str))
		// {
		// return "";
		// }
		String date = "";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fomcat);
		try {
			Date d = simpleDateFormat.parse(str);
			date = (1900 + d.getYear()) + "-" + (d.getMonth() + 1) + "-"
					+ d.getDate();
		} catch (NullPointerException e) {
			//
		} catch (ParseException e) {
			//
		}
		return date;
	}

	/**
	 * 日期格式化测试
	 *
	 * @param str
	 *            日期（yyyy-MM-dd hh:mm:ss）
	 * @return 日期（yyyy-MM-dd）
	 */
	public static String getDateFormat(String str) {
		String date = "";
		if (isEmpty(date)) {
			date += getDateFormat(str, "yyyy-MM-dd");
		}
		if (isEmpty(date)) {
			date += getDateFormat(str, "yyyy-MM-dd hh:mm:ss");
		}
		return date;
	}

	/**
	 * 得到日期的毫秒时间
	 *
	 * @param str
	 * @return
	 */
	public static long getDateTime(String str) {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date d = simpleDateFormat.parse(str);
			return d.getTime();
		} catch (NullPointerException e) {
			//
		} catch (ParseException e) {
			//
		}
		return -1;
	}
	/**
	 * 得到日期的毫秒时间
	 *
	 * @param time
	 * @return
	 */
	public static boolean isDelete(String time) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d = simpleDateFormat.parse(time);
			long l = System.currentTimeMillis();
			long l1=l-d.getTime();
			if(l1>1000*60*60*24*7){
				//如果大于7天就删除
				return true;
			}
		} catch (NullPointerException e) {
			//
		} catch (ParseException e) {
			//
		}


		return false;
	}

	/**
	 * 设置控件是否可以编辑
	 *
	 * @param view
	 *            视图
	 * @param isEnabled
	 *            是否可以编辑
	 */
	public static void setEnabled(View view, boolean isEnabled) {
		view.setEnabled(isEnabled);
		view.setFocusable(isEnabled);
		view.setFocusableInTouchMode(isEnabled);
	}

	/**
	 * 得到当前时间
	 *
	 * @return 时间
	 */
	public static String getCurrentTime() {
		final Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		String mMonth = formatTime(c.get(Calendar.MONTH) + 1);
		String mDay = formatTime(c.get(Calendar.DAY_OF_MONTH));
		String mHear = formatTime(c.get(Calendar.HOUR_OF_DAY));
		String mMinute = formatTime(c.get(Calendar.MINUTE));
		String mSecond = formatTime(c.get(Calendar.SECOND));

		String time = mYear + "-" + mMonth + "-" + mDay + " " + mHear + ":"
				+ mMinute + ":" + mSecond;
		return time;
	}

	/**
	 * 检测是否Http格式
	 *
	 * @param uri
	 * @return
	 */
	public static boolean checkHttp(String uri) {
		String PATTERN_END = "(:\\d{1,5})?" + // maybe port
				"(/|\\?|$)"; // query, path or nothing
		Pattern URL_WITH_PROTOCOL_PATTERN = Pattern
				.compile("[a-zA-Z0-9]{2,}://" + // protocol
						"[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]+)*" + // host name
						// elements
						PATTERN_END);
		Pattern URL_WITHOUT_PROTOCOL_PATTERN = Pattern
				.compile("([a-zA-Z0-9\\-]+\\.)+[a-zA-Z0-9\\-]{2,}" + // host
						// name
						// elements
						PATTERN_END);

		Matcher m = URL_WITH_PROTOCOL_PATTERN.matcher(uri);
		if (m.find() && m.start() == 0) { // match at start only
			return true;
		}
		m = URL_WITHOUT_PROTOCOL_PATTERN.matcher(uri);
		return m.find() && m.start() == 0;
	}

	/**
	 * 检测是否Http格式
	 *
	 * @param str
	 * @return
	 */
	/*
	 * public static boolean checkHttp(String str) { boolean b = false; try {
	 * Pattern p = Pattern .compile(
	 * "(http://)?([\\w\\d]+[\\.]{1})+[\\w\\d]+([/]?[\\w\\d]+[(\\x21-\\x7e)]?)+"
	 * ); Matcher m = p.matcher(str); while (m.find()) { MatchResult mr =
	 * m.toMatchResult(); //Log.d("intel=", mr.group()); if (str.length() ==
	 * mr.group().length()) { b = true; } } } catch (IllegalStateException ise)
	 * { // 没有成功,返回 b = false; } catch (PatternSyntaxException pse) { // TODO:
	 * handle exception // 正则表达式是不正确的 b = false; } return b; }
	 */
	/**
	 * 跳转到浏览器
	 *
	 * @param url
	 *            网址
	 * @return
	 */
	public static Intent goUrl(String url) {
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
		return intent;
	}

	/**
	 * 获取Mainifest的版本号
	 *
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context) {
		String version = "0.0.0";
		PackageManager packageManager = context.getPackageManager();
		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(
					context.getPackageName(), 0);
			version = packageInfo.versionName;
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
		}

		return version.trim();
	}

	/**
	 * if the net is available
	 *
	 * @return true is available
	 */
	public static boolean isConnectedNet(Context context) {

		ConnectivityManager cManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cManager.getActiveNetworkInfo();
		if (info != null && info.isAvailable()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 添加单选数据
	 *
	 * @param spinner 下拉框
	 * @param strs 字典数据数组
	 * @param selectStr 选择内容
	 * @param isMoren 是否有默认选项
	 */
	public static void addSpinner(Context context, Spinner spinner,
								  String[] strs, String selectStr, boolean isMoren) {
		ArrayList<String> arraylist = new ArrayList<String>();
		if (isMoren) {
			arraylist.add("");
		}
		for (int i = 0; i < strs.length; i++) {
			arraylist.add(strs[i]);
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
				android.R.layout.simple_spinner_item, arraylist);
		adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		int index = arraylist.indexOf(selectStr);

		if (arraylist.size() > 0 && index != -1) {
			spinner.setSelection(index);
		} else if (index == -1 && arraylist.size() > 0) {
			spinner.setSelection(0);
		}
	}

	/**
	 * 添加单选数据
	 *
	 * @param context
	 * @param spinner
	 *            下拉框
	 * @param strs
	 *            字典数据数组
	 * @param selectStr
	 *            选择内容
	 */
	public static void addSpinner(Context context, Spinner spinner,
								  String[] strs, String selectStr) {
		addSpinner(context, spinner, strs, selectStr, true);
	}

	public static String getSelectedItemPosition(Spinner spinner) {
		return (String) spinner.getSelectedItem();
	}

	/**
	 * 字符串转换成消息盒子
	 *
	 * @param results
	 *            返回的字符串
	 * @return message 消息盒子
	 */
	public static Message stringToMessage(String results) {
		Message message = null;
		// if (getState()) {
		// return message;
		// }
		if (results.equals("") || results == null) {
			return message;
		}
		message = Utils.jsonToMessage(results);// 转换成消息盒子
		return message;
	}

	public static final InputStream byte2Input(byte[] buf) {
		return new ByteArrayInputStream(buf);
	}

	public static final byte[] input2byte(InputStream inStream) {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		try {
			while ((rc = inStream.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
		} catch (IOException ioe) {

		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}

	/**
	 * 得到当前时刻(凌晨、上午、中午、下午、晚上)
	 *
	 * @return
	 */
	public static String getCurrentMoment() {
		Date mydate = new Date();
		int hour = mydate.getHours();
		if (0 <= hour && hour <= 6)
			return "凌晨";
		else if (hour > 6 && hour < 12)
			return "上午";
		else if (hour >= 12 && hour < 14)
			return "中午";
		else if (hour >= 14 && hour < 19)
			return "下午";
		else if (hour >= 19 && hour < 24)
			return "晚上";
		else
			return "今天";
	}

	/**
	 * 得到文件的后缀
	 *
	 * @param path
	 * @return
	 */
	public static String getFileExt(String path) {
		int i = path.lastIndexOf(".");
		if (i >= 0 && i != path.length()) {
			return path.substring(i + 1);
		}
		return null;
	}

	/**
	 * 得到相册图片的意图
	 *
	 * @return
	 */
	public static Intent getPhotoIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 100);
		intent.putExtra("outputY", 100);
		intent.putExtra("return-data", true);
		return intent;
	}

	public static void toLog(String tag, String message) {
		Log.d(tag, message);
	}

	/**
	 * 获取视频截图 (android2.2及以上支持)
	 *
	 * @param bm
	 * @return
	 */
	// public static Bitmap getVideoThumbnail(String path) {
	// try {
	// // 注意:android2.2及以上支持
	// Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(path,
	// Thumbnails.MINI_KIND);
	// bitmap.compress(Bitmap.CompressFormat.PNG, 100,
	// new ByteArrayOutputStream());
	// return bitmap;
	// }catch (IllegalArgumentException e) {
	// // TODO: handle exception
	// }
	// catch (Exception e) {
	// // TODO: handle exception
	// }
	// return null;
	// }
	/**
	 * 使用android的隐藏类，使用到JNI库：libmedia_jni.so
	 *
	 * @param path
	 * @return
	 */
	@TargetApi(10)
	public static Bitmap createVideoThumbnail(String path) {
		try {
			MediaMetadataRetriever m = new MediaMetadataRetriever();
			m.setDataSource(path);
			return m.getFrameAtTime();
		} catch (IllegalArgumentException e) {
			// TODO: handle exception
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/**
	 * 新视频增加后需要SDCard重新扫描才能给新增加的文件添加缩略图，灵活性差，而且不是很稳定，适合简单应用
	 *
	 * @param fileName
	 * @param fileName
	 * @return
	 */
	public static Bitmap getVideoThumbnail(Context context, String fileName) {
		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inDither = false;
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		// select condition.
		String whereClause = MediaStore.Video.Media.DATA + " = '" + fileName
				+ "'";
		Log.v("getVideoThumbnail", "where = " + whereClause);
		// colection of results.
		Cursor cursor = context.getContentResolver().query(
				MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
				new String[] { MediaStore.Video.Media._ID }, whereClause, null,
				null);
		Log.v("getVideoThumbnail", "cursor = " + cursor);
		if (cursor == null || cursor.getCount() == 0) {
			return null;
		}
		return bitmap;
	}

	/**
	 * 得到图片
	 *
	 * @param f
	 * @param size
	 * @return
	 */
	public static Bitmap decodeFile(File f, int size) {
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// The new size we want to scale to
			final int REQUIRED_SIZE = size;

			// Find the correct scale value. It should be the power of 2.
			int scale = 1;
			while (o.outWidth / scale / 2 >= REQUIRED_SIZE
					&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
				scale *= 2;

			// Decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	/**
	 * 复制文件到指定目录
	 *
	 * @param fromFile
	 * @param toFile
	 * @param rewrite
	 * @throws IOException
	 */
	public static void copyfile(File fromFile, File toFile, boolean rewrite)
			throws IOException {
		if (!fromFile.exists()) {
			return;
		}

		if (!fromFile.isFile()) {
			return;
		}
		if (!fromFile.canRead()) {
			return;
		}
		if (!toFile.getParentFile().exists()) {
			toFile.getParentFile().mkdirs();
		}
		if (toFile.exists() && rewrite) {
			toFile.delete();
		}

		// 当文件不存时，canWrite一直返回的都是false
		// if (!toFile.canWrite()) {
		// MessageDialog.openError(new Shell(),"错误信息","不能够写将要复制的目标文件" +
		// toFile.getPath());
		// Toast.makeText(this,"不能够写将要复制的目标文件", Toast.LENGTH_SHORT);
		// return ;
		// }
		try {

			FileInputStream fosfrom = new FileInputStream(fromFile);

			FileOutputStream fosto = new FileOutputStream(toFile);

			byte bt[] = new byte[1024];
			int c;
			while ((c = fosfrom.read(bt)) > 0) {
				fosto.write(bt, 0, c); // 将内容写到新文件当中
			}

			fosfrom.close();
			fosto.close();

		} catch (Exception ex) {
			Log.e("readfile", ex.getMessage());
		}
	}

	public static Bitmap zoom(String f, int thewidth) {

		try {
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			Bitmap bitmapOrg = BitmapFactory.decodeFile(f, options);

			// 获取这个图片的宽和高
			int width = bitmapOrg.getWidth();
			int height = bitmapOrg.getHeight();

			// 定义预转换成的图片的宽度和高度
			int newWidth = thewidth;
			int newHeight = (int) Math.ceil(((float) thewidth / (float) width)
					* (float) height);

			// 计算缩放率，新尺寸除原始尺寸
			float scaleWidth = ((float) newWidth) / width;
			float scaleHeight = ((float) newHeight) / height;

			// 创建操作图片用的matrix对象
			Matrix matrix = new Matrix();

			// 缩放图片动作
			matrix.postScale(scaleWidth, scaleHeight);

			// 旋转图片 动作
			// matrix.postRotate(45);

			// 创建新的图片
			bitmapOrg = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height,
					matrix, true);
			return bitmapOrg;
		} /*
		 * catch (FileNotFoundException e) { e.printStackTrace(); return null; }
		 */catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Bitmap zoom(String f, String n, int thewidth) {

		try {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
				Bitmap bitmap= BitmapFactory.decodeFile(f);
				boolean v=saveBitmap(bitmap);
			}else {
				File sourceFile = new File(f);
				File targetFile = new File(n);
				// 新建文件输入流并对它进行缓冲
				FileInputStream input = new FileInputStream(sourceFile);
				BufferedInputStream inBuff = new BufferedInputStream(input);
				// 新建文件输出流并对它进行缓冲
				FileOutputStream output =new FileOutputStream(targetFile);
				BufferedOutputStream outBuff = new BufferedOutputStream(output);

				// 缓冲数组
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = inBuff.read(b)) != -1) {
					outBuff.write(b, 0, len);
				}
				// 刷新此缓冲的输出流
				outBuff.flush();

				// 关闭流
				inBuff.close();
				input.close();
				outBuff.close();
				output.close();
			}


			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 1;
			Bitmap bitmapOrg = BitmapFactory.decodeFile(f, options);

			// 获取这个图片的宽和高
			int width = bitmapOrg.getWidth();
			int height = bitmapOrg.getHeight();

			// 定义预转换成的图片的宽度和高度
			int newWidth = thewidth;
			int newHeight = (int) Math.ceil(((float) thewidth / (float) width)
					* (float) height);

			// 计算缩放率，新尺寸除原始尺寸
			float scaleWidth = ((float) newWidth) / width;
			float scaleHeight = ((float) newHeight) / height;

			// 创建操作图片用的matrix对象
			Matrix matrix = new Matrix();

			// 缩放图片动作
			matrix.postScale(scaleWidth, scaleHeight);

			// 旋转图片 动作
			// matrix.postRotate(45);

			// 创建新的图片
			bitmapOrg = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height,
					matrix, true);
			return bitmapOrg;
		} /*
		 * catch (FileNotFoundException e) { e.printStackTrace(); return null; }
		 */catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static boolean saveBitmap(Bitmap bitmap) throws IOException {
		File eFile = Environment.getExternalStorageDirectory();
		File mDirectory = new File(eFile.toString() + "/Image");
		if (!mDirectory.exists()) {
			mDirectory.mkdirs();
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyyMMddHHmmssSSS");
		String dateStr = dateFormat.format(new Date());
		File imageFile = new File(mDirectory, "zm"+dateStr+".jpg");
		FileOutputStream out;
		try {
			out = new FileOutputStream(imageFile);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)) {
				out.flush();
				out.close();
			}

			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
//	public static Bitmap zoom(String f, String n, int thewidth) {
//
//		try {
//
//			// int bytesum = 0;
//			// int byteread = 0;
//			// File oldfile = new File(f);
//			// if (oldfile.exists()) { // 文件存在时
//			// InputStream inStream = new FileInputStream(f); // 读入原文件
//			// FileOutputStream fs = new FileOutputStream(n);
//			// byte[] buffer = new byte[1444];
//			// int length;
//			// while ((byteread = inStream.read(buffer)) != -1) {
//			// bytesum += byteread; // 字节数 文件大小
//			// System.out.println(bytesum);
//			// fs.write(buffer, 0, byteread);
//			// }
//			// inStream.close();
//			// }
//
//			File sourceFile = new File(f);
//			File targetFile = new File(n);
//
//			// 新建文件输入流并对它进行缓冲
//			FileInputStream input = new FileInputStream(sourceFile);
//			BufferedInputStream inBuff = new BufferedInputStream(input);
//
//			// 新建文件输出流并对它进行缓冲
//			FileOutputStream output = new FileOutputStream(targetFile);
//			BufferedOutputStream outBuff = new BufferedOutputStream(output);
//
//			// 缓冲数组
//			byte[] b = new byte[1024 * 5];
//			int len;
//			while ((len = inBuff.read(b)) != -1) {
//				outBuff.write(b, 0, len);
//			}
//			// 刷新此缓冲的输出流
//			outBuff.flush();
//
//			// 关闭流
//			inBuff.close();
//			outBuff.close();
//			output.close();
//			input.close();
//
//			BitmapFactory.Options options = new BitmapFactory.Options();
//			options.inSampleSize = 1;
//			Bitmap bitmapOrg = BitmapFactory.decodeFile(n, options);
//
//			// 获取这个图片的宽和高
//			int width = bitmapOrg.getWidth();
//			int height = bitmapOrg.getHeight();
//
//			// 定义预转换成的图片的宽度和高度
//			int newWidth = thewidth;
//			int newHeight = (int) Math.ceil(((float) thewidth / (float) width)
//					* (float) height);
//
//			// 计算缩放率，新尺寸除原始尺寸
//			float scaleWidth = ((float) newWidth) / width;
//			float scaleHeight = ((float) newHeight) / height;
//
//			// 创建操作图片用的matrix对象
//			Matrix matrix = new Matrix();
//
//			// 缩放图片动作
//			matrix.postScale(scaleWidth, scaleHeight);
//
//			// 旋转图片 动作
//			// matrix.postRotate(45);
//
//			// 创建新的图片
//			bitmapOrg = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height,
//					matrix, true);
//			return bitmapOrg;
//		} /*
//		 * catch (FileNotFoundException e) { e.printStackTrace(); return null; }
//		 */catch (Exception e) {
//			e.printStackTrace();
//			return null;
//		}
//	}





	/**
	 * 判断是否I-OID码
	 *
	 * @param string
	 * @return
	 */
	public static boolean isIOID(String string) {

		return true;
	}

	/**
	 * activity切换动画
	 *
	 * @param context
	 */
	public static void randomAnim(Context context) {

		int i = (int) (Math.random() * 5 + 0);
		switch (i) {
			case 0:
				((Activity) context).overridePendingTransition(R.anim.fade,
						R.anim.hold);
				break;
			/*
			 * case 1: ((Activity)
			 * context).overridePendingTransition(R.anim.my_scale_action,
			 * R.anim.my_alpha_action); break;
			 */
			/*
			 * case 2: ((Activity)
			 * context).overridePendingTransition(R.anim.scale_rotate,
			 * R.anim.my_alpha_action); break;
			 */
			/*
			 * case 3: ((Activity)
			 * context).overridePendingTransition(R.anim.scale_translate_rotate,
			 * R.anim.my_alpha_action); break;
			 */
			case 1:
				((Activity) context).overridePendingTransition(
						R.anim.scale_translate, R.anim.my_alpha_action);
				break;
			/*
			 * case 5: ((Activity)
			 * context).overridePendingTransition(R.anim.hyperspace_in,
			 * R.anim.hyperspace_out); break;
			 */
			case 2:
				((Activity) context).overridePendingTransition(R.anim.push_left_in,
						R.anim.push_left_out);
				break;
			case 3:
				((Activity) context).overridePendingTransition(R.anim.push_up_in,
						R.anim.push_up_out);
				break;
			/*
			 * case 4: ((Activity)
			 * context).overridePendingTransition(R.anim.slide_right,
			 * R.anim.slide_left); break;
			 */
			/*
			 * case 9: ((Activity)
			 * context).overridePendingTransition(R.anim.wave_scale,
			 * R.anim.my_alpha_action); break;
			 */
			case 4:
				((Activity) context).overridePendingTransition(R.anim.zoom_enter,
						R.anim.zoom_exit);
				break;
			case 5:
				((Activity) context).overridePendingTransition(R.anim.slide_up_in,
						R.anim.slide_down_out);
				break;
		}
	}

	/**
	 * 截取码前缀
	 *
	 * @param code
	 * @return
	 */
	public static String getCodeStr(String code) {
		if (code.contains("http://s.idcode.org.cn/m?code=")) {
			code = code.replace("http://s.idcode.org.cn/m?code=", "").trim();
		} else if (code.contains("http://s.i-oid.org.cn/q.aspx?ewm=")) {
			code = code.replace("http://s.i-oid.org.cn/q.aspx?ewm=", "").trim();
		}
		return code;
	}
	public static String getTail_Code(String code){
		return code.substring(code.indexOf("="),code.length());
	}
	/**
	 * 是否为idcode码
	 *
	 * @param code
	 * @return
	 */
	public static String getIDcodeStr(String code) {
		String codeStr = "";
		if (code.indexOf(".") == -1) {
			if (code.trim().length() == 18) {
				if (isNumeric(code)) {
					codeStr = code.trim();
				}
			}
		} else {
			String[] codeArr = code.split("\\.");
			if (codeArr.length == 9 || codeArr.length == 8) {
				String code1 = codeArr[codeArr.length - 2];
				if (isNumeric(code1)) {
					codeStr = code1.trim();
				}
			}

		}

		return codeStr;
	}

	/* 解决4.4以上图片url */

	/**
	 * 根据Uri获取图片绝对路径，解决Android4.4以上版本Uri转换
	 *
	 * @param context
	 * @param imageUri
	 * @author yaoxing
	 * @date 2014-10-12
	 */
	@TargetApi(19)
	public static String getImageAbsolutePath(Context context, Uri imageUri) {
		if (context == null || imageUri == null)
			return null;
		// android 4.4 对应的是19 测试被给的uri是被DocumentProvider 返回的
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
				&& DocumentsContract.isDocumentUri(context, imageUri)) {
			if (isExternalStorageDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}
			} else if (isDownloadsDocument(imageUri)) {
				String id = DocumentsContract.getDocumentId(imageUri);
				Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));
				return getDataColumn(context, contentUri, null, null);
			} else if (isMediaDocument(imageUri)) {
				String docId = DocumentsContract.getDocumentId(imageUri);
				String[] split = docId.split(":");
				String type = split[0];
				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}
				String selection = MediaStore.Images.Media._ID + "=?";
				String[] selectionArgs = new String[] { split[1] };
				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		} // MediaStore (and general)
		else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
			// Return the remote address
			if (isGooglePhotosUri(imageUri))
				return imageUri.getLastPathSegment();
			return getDataColumn(context, imageUri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
			return imageUri.getPath();
		}
		return null;
	}

	public static String getDataColumn(Context context, Uri uri,
									   String selection, String[] selectionArgs) {
		Cursor cursor = null;
		String column = MediaStore.Images.Media.DATA;
		String[] projection = { column };
		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 *
	 * @param matrix
	 * @return
	 */
	private static int getFinderPatternWidth(BitMatrix matrix) {
		int W = matrix.getWidth();
		int H = matrix.getHeight();
		int length = 0;
		boolean flag = false;
		for (int y = 0; y < H; y++) {
			for (int x = 0; x < W; x++) {
				if (matrix.get(x, y) == true) {
					flag = true;
					length++;
				} else {
					if (flag != false) {
						return x;
					}
				}
			}
		}
		return length;
	}

	/**
	 * 生成一个二维码图像
	 *
	 * @param url
	 *            传入的字符串，通常是一个URL
	 * @param QR_WIDTH
	 *            宽度（像素值px）
	 * @param QR_HEIGHT
	 *            高度（像素值px）
	 * @return
	 */
	public static final Bitmap create2DCoderBitmap(String url, int QR_WIDTH,
												   int QR_HEIGHT) {
		try {
			// 判断URL合法性
			if (url == null || "".equals(url) || url.length() < 1) {
				return null;
			}
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			// 图像数据转换，使用了矩阵转换
			BitMatrix bitMatrix = new QRCodeWriter().encode(url,
					BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
			int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
			int H = bitMatrix.getHeight();
			int W = bitMatrix.getWidth();
			int L = getFinderPatternWidth(bitMatrix) + 3;
			Color redColor = new Color();
			redColor.rgb(182, 0, 5);
			int redColorInt = redColor.argb(0xff, 182, 0, 5);
			Color greenColor = new Color();
			greenColor.rgb(0, 124, 54);
			int greenColorInt = greenColor.argb(0xff, 0, 124, 54);
			Color blueColor = new Color();
			blueColor.rgb(0, 64, 152);
			int blueColorInt = blueColor.argb(0xff, 0, 64, 152);
			// 下面这里按照二维码的算法，逐个生成二维码的图片，
			// 两个for循环是图片横列扫描的结果
			// for (int y = 0; y < QR_HEIGHT; y++) {
			// for (int x = 0; x < QR_WIDTH; x++) {
			// if (bitMatrix.get(x, y)) {
			// pixels[y * QR_WIDTH + x] = 0xff000000;
			// } else {
			// pixels[y * QR_WIDTH + x] = 0xffffffff;
			// }
			// }
			// }
			for (int y = 0; y < H; y++) {
				for (int x = 0; x < W; x++) {
					if (x > 0 && x < L && y > 0 && y < L) {
						pixels[y * W + x] = bitMatrix.get(x, y) ? redColorInt
								: Color.WHITE;
					} else if (x > (W - L) && x < H && y > 0 && y < L) {
						pixels[y * W + x] = bitMatrix.get(x, y) ? blueColorInt
								: Color.WHITE;
					} else if (x > 0 && x < L && y > (H - L) && y < H) {
						pixels[y * W + x] = bitMatrix.get(x, y) ? greenColorInt
								: Color.WHITE;
					} else {
						pixels[y * W + x] = bitMatrix.get(x, y) ? Color.BLACK
								: Color.WHITE;
					}
				}
			}
			// 生成二维码图片的格式，使用ARGB_8888
			// Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
			// Bitmap.Config.ARGB_8888);
			// int[] colors = { Color.TRANSPARENT, Color.TRANSPARENT,
			// Color.TRANSPARENT };
			Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
					Bitmap.Config.ARGB_8888);
			bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
			// 显示到一个ImageView上面
			// sweepIV.setImageBitmap(bitmap);
			return bitmap;
		} catch (Exception e) {
			Log.i("log", "生成二维码错误" + e.getMessage());
			return null;
		}
	}

	/**
	 * 从assets 文件夹中获取文件并读取数据
	 *
	 * @param fileName
	 * @return
	 */
	public static String getFromAssets(Context context, String fileName) {
		InputStream is = null;
		InputStreamReader reader = null;
		BufferedReader bufferedReader = null;
		StringBuffer buffer = new StringBuffer("");
		try {
			is = context.getResources().getAssets().open(fileName);
			reader = new InputStreamReader(is);
			bufferedReader = new BufferedReader(reader);
			String str;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
				buffer.append("\n");
			}
			is.close();
			reader.close();
			bufferedReader.close();
		} catch (Exception e) {
			buffer.setLength(0);
			try {
				if (is != null)
					is.close();
				if (reader != null)
					reader.close();
				if (bufferedReader != null)
					bufferedReader.close();
			} catch (Exception ee) {
				ee.printStackTrace();
			}
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * 保存二维码图片
	 */
	public static String saveEWMBitmapToFile(Bitmap ewmBit, String storeName) {
		String pathStr = "";
		File dir = new File("/sdcard///AgricultureSystem//EWMImage//",
				storeName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File("/sdcard///AgricultureSystem//EWMImage//",
				storeName);
		if (file.exists()) {
			file.delete();
		}
		FileOutputStream out;
		try {
			out = new FileOutputStream(file);
			if (ewmBit.compress(Bitmap.CompressFormat.PNG, 100, out)) {
				out.flush();
				out.close();
			}
			pathStr = "/sdcard/AgricultureSystem/EWMImage/" + storeName;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return pathStr;
	}

	/**
	 * 获取指定文件大小
	 *
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static long getFileSize(File file) throws Exception {
		long size = 0;
		FileInputStream fis = null;
		if (file.exists()) {
			fis = new FileInputStream(file);
			size = fis.available();
		} else {
			// file.createNewFile();
			Log.e("获取文件大小", "文件不存在!");
		}
		if (fis != null) {
			fis.close();
		}
		return size;
	}

	public static final int NETTYPE_NULL = 0x00;
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;
	public static final String VERSION_HEAD = "V";

	/**
	 * 获取当前网络类型
	 *
	 * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
	 */
	public static int getNetworkType(Context context) {
		int netType = NETTYPE_NULL;
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			if (!TextUtils.isEmpty(extraInfo)) {
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}
	public static boolean isDateOneBigger(String SelectTime, String DateTime) {
		boolean isBigger = false;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		Date Selectdt = null;
		Date Nowdt = null;
		try {
			Selectdt = sdf.parse(SelectTime);
			Nowdt = sdf.parse(DateTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (Selectdt.getTime() <= Nowdt.getTime()) {
			isBigger = true;
		} else if (Selectdt.getTime() > Nowdt.getTime()) {
			isBigger = false;
		}
		return isBigger;
	}
	public static void showShortToast(Context context, String msg){
		Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
	}
	public static String  getTime(){
		SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy年MM月dd日");
		Date curDate =  new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}
	public static void showLogE(String tag, String msg){
		if(!DEBUG){
			return;
		}
		Log.e(tag, msg);
	}
	/**
	 * 请求中继
	 *
	 * @param model 待传对象
	 * @param msgType 协议值
	 *
	 * @return post内容
	 * */
	public static final boolean DEBUG = false;
	public static String getPostRequest(Object model, int msgType){
		return JsonUtils.toJSON(model);
	}
	/**
	 * 响应中继
	 * @param response 返回内容
	 *
	 * @return 消息内容
	 * */
	public static String getPostResult(String response){
		com.ioid.model.Message message = JsonUtils.jsonToMessage(response);
		String content = JsonUtils.getMessageContent(message);
		Utils.showLogE("response content", content);
		return content;
	}

	/**
	 * Java中的md5
	 * @param content 输入的值
	 * @return 输出md5加密后的值
	 */
	public static String md5Java(String content) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(content.getBytes());
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("NoSuchAlgorithmException", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10) {
				hex.append(0);
			}
			hex.append(Integer.toHexString(b & 0xff));
		}

		return hex.toString();

	}

	public static Integer[] getNumbers(String quantitySpec) {
		Integer[] countsArray = new Integer[0];//=new Integer[3];
		if(quantitySpec!=null&& !StringUtils.isEmpty(quantitySpec)){
			ArrayList<Integer> counts = new ArrayList<>();
			Pattern pattern = Pattern.compile("\\d+");
			Matcher matcher = pattern.matcher(quantitySpec);
			while(matcher.find()) {
				counts.add(Integer.parseInt(matcher.group()));
			}
			countsArray= counts.toArray(new Integer[counts.size()]);
		}
		return countsArray;
	}
}
